const path = require('path')
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const RedisStore = require('koa-redis')
const koaStatic = require('koa-static')

const {
    REDIS_CONF
} = require('./conf/db')
const {
    isProd
} = require('./utils/env')
const {
    SESSION_SECRET_KEY
} = require('./conf/secretKeys')


// 路由
const blogHomeAPIRouter = require('./routes/api/blog-home')
const blogViewRouter = require('./routes/view/blog')
const utilsAPIRouter = require('./routes/api/utils')
const userViewRouter = require('./routes/view/user')
const userAPIRouter = require('./routes/api/user')
const errorViewRouter = require('./routes/view/error')

// error handler
let onerrorConf = {}
if (isProd) {
    onerrorConf = {
        redirect: '/error'
    }
}
onerror(app, onerrorConf)

// middlewares
app.use(
    bodyparser({
        enableTypes: ['json', 'form', 'text']
    })
)
app.use(json())
app.use(logger())
app.use(koaStatic(__dirname + '/public'))
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')))

app.use(
    views(__dirname + '/views', {
        extension: 'ejs'
    })
)

// session 配置
app.keys = [SESSION_SECRET_KEY]
app.use(
    session({
        key: 'weibo.sid', // cookie name默认是 'koa.sid'
        prefix: 'weibo:sess:', // redis key 的前缀 默认是'koa:sess:'
        cookie: {
            path: '/',
            httpOnly: true, // 不允许客户端修改cookie
            maxAge: 24 * 60 * 60 * 1000 // ms
        },
        //ttl: 24 * 60 * 60 * 1000, 默认和maxAge 一样
        store: RedisStore({
            all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
        })
    })
)

// routes
app.use(blogHomeAPIRouter.routes(), blogHomeAPIRouter.allowedMethods())
app.use(blogViewRouter.routes(), blogViewRouter.allowedMethods())
app.use(utilsAPIRouter.routes(), utilsAPIRouter.allowedMethods())
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods())
// 404 error 路由 要放在最下面
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
})

module.exports = app